package com.usian.quartz;

import com.usian.pojo.LocalMessage;
import com.usian.pojo.TbOrder;
import com.usian.redis.RedisClient;
import com.usian.sender.MQSender;
import com.usian.service.LocalMessageService;
import com.usian.service.OrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

public class OrderQuartz implements Job {

    @Autowired
    private OrderService orderService;

    @Autowired
    RedisClient redisClient;

    @Autowired
    MQSender mqSender;

    @Autowired
    LocalMessageService localMessageService;

    /**
     * 关闭超时订单
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //解决quartz集群任务重复执行
        if(redisClient.setnx("SETNX_LOCK_ORDER_KEY",ip,30)) {
            //查询超时订单
            List<TbOrder> orderList = orderService.selectOvertimeOrder();
            for (TbOrder tbOrder : orderList) {
                //关闭超时订单
                orderService.updateOverTimeTbOrder(tbOrder);
                //把超时订单的上游库存加回去
                orderService.updateTbItemByOrderId(tbOrder.getOrderId());
            }

            //分布式事务第三个策略 定时任务 获取发送不成功的本地消息记录表信息
            List<LocalMessage> list = localMessageService.selectlocalMessageByStatus();
            for (LocalMessage localMessage : list) {
                mqSender.sendMsg(localMessage);
            }

            //删除分布式锁 setnx 的设置
            redisClient.del("SETNX_LOCK_ORDER_KEY");
            System.out.println("=============删除超时的订单=========");
        }else{
            System.out.println(
                    "============机器："+ip+" 占用分布式锁，任务正在执行=======================");
        }



    }
}
